<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <span slot="footer" class="dialog-footer">
     <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
     <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    patrolPlanDetail,
    patrolPlanUpdate,
    patrolPlanAdd,
    patrolModelList
  } from '@/api/risk/patrol'
  import {
    getInstitutionList
  } from '@/api/system/institution'
  import {
    getDeptList,getUserList
  } from '@/api/risk/dept'
  import { treeDataChild } from '@/api/risk/treeData'
  import VForm from "@/components/VForm/index";
  import { collectBuildingProjectList } from '@/api/build/project'
  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "80%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      bClassifyOptions:{},
      planTypeOptions:{}
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiLargeType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'planTypeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'planCycleOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planCycle'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptionsForm':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiSmallType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'modelList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='modelId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiLargeType':{
        handler(newVal, oldVal) {
          this.watchChangeLargeType()
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiSmallType':{
        handler(newVal, oldVal) {
          if(newVal){
            this.watchChangeSmallType()
          }
        },
        deep: true,
        immediate: true
      },
      'belongUnitIdList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='execUnitId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'openType':{
        handler(newVal, oldVal) {
          // 判断是否详情，添加不可编辑标识
          this.formData.options.forEach(t=>{
            t.disabled = newVal=='detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      },
      'buildingOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'buildingId') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan:1,
        dict:{},
        formData: {
          form: {
            id:"",
            planName:"",
            busiLargeType:"",
            busiSmallType:"",
            modelId:"",
            planType:"",
            planCycle:"",
            execUnitId:[],
            execUnit:"",
            planStartDate:"",
            planEndDate:"",
            remark:"",
            buildingId: "",
          },
          options: [

            {
              title: "所属工地",
              key: "buildingId",
              type: "select",
              multiple: false,
              option: {
                data: this.buildingOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "projectName", // 指定label对应data的字段
                  value: "id", //指定value对应data的字段
                }
              }
            },

            {
              title: "计划名称",
              key: "planName",
              type: "text",
            },
            {
              title: "业务专题大类",
              key: "busiLargeType",
              type: "select",
              multiple:false,
              event: 'changeLargeType',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "业务专题细类",
              key: "busiSmallType",
              type: "select",
              multiple:false,
              event: 'changeSmallType',
              option: {
                data: this.sClassifyOptionsForm,
                props: {
                  key: "code", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "code", // 指定value对应data的字段
                },
              },
            },
            {
              title: "巡查表单",
              key: "modelId",
              type: "select",
              multiple:false,
              option: {
                data: this.modelList,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "modelName", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划巡检类型",
              key: "planType",
              type: "select",
              multiple:false,
              option: {
                data: this.planTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划周期",
              key: "planCycle",
              type: "select",
              multiple:false,
              option: {
                data: this.planCycleOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "执行单位",
              key: "execUnitId",
              type: "select",
              multiple:true,
              option: {
                data: this.belongUnitIdList,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "name", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划开始日期",
              key: "planStartDate",
              type: "date",
            },
            {
              title: "计划结束日期",
              key: "planEndDate",
              type: "date",
            },
            {
              title: "计划描述",
              key: "remark",
              type: "textarea",
              columnWidth: 'w100max',
            },
          ],
          rules: {
            planName :[
              { required: true, message: '请输入', trigger: 'blur' },
              {max:64, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            planType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            modelId :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            busiLargeType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            busiSmallType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            // planCycle :[
            //   { required: this.getRequire(), message: '请选择', trigger: 'change' },
            // ],
            execUnitId :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            planStartDate :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            planEndDate :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            remark :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
          },
          labelWidth: "140px",
        },
        // 字典
        belongUnitIdList:[],
        sClassifyOptionsForm:[],
        modelList:[],
        planCycleOptions:[],
        buildingOptions: [],
      };
    },
    methods: {
      noBlank(val) {
        if (val != "" && val != null && val != undefined) {
          return true;
        }
        return false;
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      watchChangeSmallType(){
        let disableFlag = this.openType=='detail' ? 1 : 0
        let delFlag =  this.openType=='detail' ? 1 : 0
         let data = {
           busiLargeType:this.formData.form.busiLargeType,
           busiSmallType:this.formData.form.busiSmallType,
           disableFlag:disableFlag,
           delFlag:delFlag
         }
         patrolModelList(data).then(res=>{
           if(res.code==200){
             this.modelList = res.data
           }
         })
      },
      watchChangeLargeType(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.busiLargeType
        treeDataChild(queryData).then(res=>{
          if(res.code==200) {
            this.sClassifyOptionsForm = res.data
          }
        })
      },
      changeLargeType(){
        this.formData.form.busiSmallType = ''
      },
      changeSmallType(){
          this.formData.form.modelId = ''
      },
      initData(){
          this.formData.form.id = "",
          this.formData.form.planName = "",
          this.formData.form.busiLargeType = "",
          this.formData.form.busiSmallType = "",
          this.formData.form.modelId = "",
          this.formData.form.planType = "",
          this.formData.form.planCycle = "",
          this.formData.form.execUnitId = [],
          this.formData.form.execUnit = "",
          this.formData.form.planStartDate = "",
          this.formData.form.planEndDate = "",
          this.formData.form.remark = ""
          this.modelList= []
          this.sClassifyOptionsForm = []
          this.belongUnitIdList = []
      },
      sure(){
        console.log('sure===',this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res=>{
          if(this.formData.form.planType==1 && !this.noBlank(this.formData.form.planCycle)){
            this.$message.warning("计划型巡查计划需选择计划周期")
            return
          }
          let tempName= []
          this.formData.form.execUnitId.forEach(t=>{
            let item = this.belongUnitIdList.find(x=>x.id == t)
            if(undefined!=item){
              tempName.push(item.name)
            }
          })
          let tempParam = {
              ...this.formData.form,
              execUnitId:this.formData.form.execUnitId.join(","),
              execUnit:tempName.join(",")
          }
          if(this.openType == "add"){
            this.add(tempParam)
          }else{
            this.update(tempParam)
          }
        })
      },
      add(tempParam){
        tempParam.id = null
        patrolPlanAdd(tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      update(tempParam){
        patrolPlanUpdate(tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('success')
      },
      close(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('close')
      },
      getUnitListData(){
        // 仅 市单位使用当前页面 （查询下级单位）
        let deptId = this.$store.state.account.user.deptId
        // getInstitutionList({fatherUnitId: deptId}).then(res=>{
        //     if(res.code==200){
        //       this.belongUnitIdList = res.data.map(t=>{ return {id:t.unitId, name:t.unitName} })
        //     }
        // })

        getDeptList({deptId: deptId}).then(res=>{
          if(res.code==200){
            this.belongUnitIdList = res.data.map(t=>{ return {id:t.deptId, name:t.deptName} })
          }
        })

        // this.belongUnitIdList = [{id:"1",name:"天河区政府"},{id:"2",name:"海珠区政府"}]
      },
      getBuildingList() {
        collectBuildingProjectList().then(res => {
          if (res.code == 200) {
            this.buildingOptions = res.data
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      getData(){
        this.planCycleOptions = []
        this.$commonJs.filterDataDict("patrolPlanCycle",this.planCycleOptions)
        this.getUnitListData();
        this.getBuildingList();
        if(this.openType!="add"){
          patrolPlanDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data
              this.$set(this.formData.form, "execUnitId",  res.data.execUnitId.split(","))
              console.log("this.formData.form ====?",this.formData.form )
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
</style>
